//watch div
var html = '';
var htmlview = '';
var divwatcher = function (intervalfunc) {
	  var checking = setInterval(function() {
		  $(intervalfunc);
	  },100);
};
//loading function
var wait_block = function(wsubmitter, text) {
	jQuery('#' + wsubmitter + ' #objwait').remove();
    var objwait = '<div id="objwait" style="position:absolute; background:transparent; ' +
                               'width:100%; height:100%; opacity:0.50; moz-opacity:0.50; top:0; left:0; ' +
                               'filter:alpha(opacity=50);" align="center">' +
                               '<img style="margin:10% 0 0 0;" src="'+ baseurl +'/img-pack/application/pictos/ajax-loader.gif">'+
                               '<br/><br/><small>'+text+'</small></div>';

    jQuery('input, textarea, select').attr('readonly', 'readonly');
    jQuery('#' + wsubmitter).append(objwait);
    
     jQuery('#' + wsubmitter).ajaxError(function(request, settings){
    	jQuery('#' + wsubmitter + ' #objwait').fadeOut();
    	jQuery('input, textarea, select').removeAttr('readonly');
    });
    
    jQuery('#' + wsubmitter).ajaxSuccess(function(request, settings){
    	jQuery('#' + wsubmitter + ' #objwait').fadeOut();
    	jQuery('input, textarea, select').removeAttr('readonly');
    });
	  
};

//pathfinder helper
var pathfinder = function (jElement) {
	
	//block height
	if ($('li#root ul li').length >= 2) {
		$('#pathfinder-rooter').css({
			height: '54px',
			overflow: 'hidden'
		});
		$('#pathfinder-navigator').css('visibility', 'visible');
	}
	else {
		$('#pathfinder-rooter').removeAttr('style');
		$('#pathfinder-navigator').css('visibility', 'hidden');
	}
	
	//create path
	_text = ($(jElement).html() != '') ? $(jElement).html() : $(jElement).attr('title');
	$text = (_text.length > 24) ? _text.substr(0, 19) + '(...)' : _text;

	_span = '';
	//get counter
	$path = '<li style="display:none;" title="'+ $(jElement).html() +'" url="'+ $(jElement).attr('url') +'" class="path-element" id="path-'+ $(jElement).attr('id') +'">'+ $text + '<span id="'+$(jElement).attr('id') + '-tmp'+'">...</span>'  + '<ul></ul></li>';

	if ($(jElement).attr('counter')) {
		$.ajax({
			cache: true,
			url: $(jElement).attr('counter'),
			success: function (message) {
				$('.path-element-counter').show();
				_span = '<span class="path-element-counter ">TOUS (<em  old-query="'+ $(jElement).attr('counter') +'">'+ message +'</em>)</span>';
				$(_span).insertBefore($('#' + $(jElement).attr('id') + '-tmp'));
				$('#' + $(jElement).attr('id') + '-tmp').remove();
			}
		});
	} 
	
	
	
	if ($(jElement).attr('parent') == '0') {
		$('li#root ul').html($path).show();
	}
	else {
		$('li#root ul li#path-' + $(jElement).attr('parent') + ' ul').html($path).show();
	}
	//add selected
	$('#path-'+ $(jElement).attr('id')).parents('ul#pathroot').find('li').each(function() {
		if ($(this).attr('id') && $(this).attr('id') != 'path-' + $(jElement).attr('id')) {
			$className = $(this).attr('id') + '-selected';
			$(this).removeClass($className).removeClass('selected');
		}
	});
	
	$className = $('#path-'+ $(jElement).attr('id')).attr('id') + '-selected';
	$('#path-'+ $(jElement).attr('id')).addClass($className); // patch for all .addClass('selected')
	//$('.ihm-content').parent().equalHeight();
	// $('#ihm-content').css('height', $('.ihm-content').height() - ($('#pathfinder-rooter').height() + $('.abc').height())); 
	//effect for show
	$('#path-'+ $(jElement).attr('id')).slideDown(function () {

		if ($('.path-element').length > 3) { 
			position+=25; 
		}
		else { 
			position = 0; 
		}
		$('#pathfinder-rooter').animate({scrollTop: position});
		
	});

}; 

//add jquery helper for height
(function($) {
	

	$.fn.equalHeight = function(){
        var height = 0,
                reset = $.browser.msie ? "1%" : "auto";

        return this
                .css("height", reset)
                .each(function() {
                        height = Math.max(height, this.offsetHeight);
                })
                .css("height", height)
                .each(function() {
                        var h = this.offsetHeight;
                        if (h > height) {
                                $(this).css("height", height - (h - height));
                        };
                });

    };

})(jQuery);

var position = 0;

//document ready
$(document).ready(function (e) {
	
   //create lang js file if exists
    if (i118n != '') {
    	$.ajax({
		  url: i118n,
		  async: false,
		  dataType: 'json',
		  success: function (data) {
    		$.each(data, function(i,item){
    			eval(i.replace(/ /gi, '_') + ' = "' + item + '";');
    		});
		  },complete: function() {

			    //account root
			    if ($('#count-root')) {
			    	$.get($('#count-root').attr('old-query'), '', function(msg) {
			    	    $('#count-root').html(msg);
			    	});
			    } 
		  }
		});
    }
	
    
	//menu helper
	//$('#ihm-content').css('height', $('.ihm-content').height() - $('#ihm-pathfinder').height()); 
	
	//navigator
	$('#pathfinder-navigator img').live('click', function () {
		oldposition = position;
		if ($(this).hasClass('top')) {
			position-= 25;
		}
		else {
			position+= 25;
		}
		
		if (position >= 0 && position <= $('#pathfinder-rooter')[0].scrollHeight) {
			$('#pathfinder-rooter').animate({scrollTop: position});
		}
		else {
			position = oldposition;
		}
	});
	
	//element pathfinder
	$('li.path-element').live('click',function () {
		// &&  !$(this).hasClass($(this).attr('id') + '-selected')
		if ($(this).attr('url')) {
			$element = $(this);
			access_path($element);
		}
		return false;
	});
	
	//watch listing
	divwatcher(function (e) {
		var newhtml = $('#ihm-content-listing').html();
	    if (html != newhtml) {
	    	html = newhtml;
	    	//check if listing < 17
	    	if ($('#ihm-content-listing').find('li').length > 17) {
	    		$('#ihm-scrollbar').css('visibility', 'visible');
	    		$('.abc').fadeIn();
	    	}
	    	else {
	    		$('#ihm-scrollbar').css('visibility', 'hidden');
	    		page = 2;
	    		if ($('.abc .content li.selected').length == 0) {
	    			//$('.ihm-content').parent().equalHeight();
	    			$('.abc').fadeOut();
	    		}
	    	}
	    	//check toolbox
	    	toolbox();
	    }
	});
	
	//watch listing
	divwatcher(function (e) {
		if ($('li#root ul li').length <= 2) {
			$('#pathfinder-rooter').removeAttr('style');
			$('#pathfinder-navigator').css('visibility', 'hidden');
		}
	});
	
	//watch view
	divwatcher(function (e) {
		var newhtml = $('#ihm-view').html();
	    if (htmlview != newhtml) {
	    	
	    	//calcul offset from element
	    	height = 0;
	    	$('#ihm-view .element').each(function () {
	    		height += $(this)[0].offsetHeight;
	    	}); 
	    	
	    	$i = 0;
	    	$('#ihm-view .element').each(function () { 
	    		if ($(this).css('display') != 'none') {
	    			$i++;
	    		}
	    	});
	    	
	    	if ((height-30) > $('#ihm-view').height()) {
	    		if ($('#ihm-view-scrollbar').css('display') == 'none') {
		    		if (!$("#ihm-view-scrollbar").hasClass('ui-slider')) {
		    			$("#ihm-view-scrollbar").css('height', $("#ihm-view").height() - 30);
			    		var slider = $("#ihm-view-scrollbar").empty().slider({
			    			orientation: 'vertical',
			    	        change: function (e, ui) {
				    			var maxScroll = $("#ihm-view").attr("scrollHeight") - $("#ihm-view").height();
				    		  	$("#ihm-view").animate({scrollTop: ((100 - ui.value) * (maxScroll / 100))  }, 'slow');
			    			},
			    	        slide: function (e, ui) {
			    				var maxScroll = $("#ihm-view").attr("scrollHeight") - $("#ihm-view").height();
			    				$("#ihm-view").attr({scrollTop: ((100 - ui.value) * (maxScroll / 100)) }, 'slow');
			    			},
			    	        animate: true,
			    	        value:100
			    	    });
		    		}
		    		// show scrollbar
		    		$('#ihm-view-scrollbar').show();
		    		
		    	}
	    	}
	    	else {
	    		$('#ihm-view-scrollbar').hide();
	    	}
	    }
	});
	
	//modal manager
	$('.modal, .popup, #ihm-toolbox .generic').live('click', function () {
		//escape menu-root
		if (!$(this).hasClass('menu-root')) {
			$link = $(this);
			$.fancybox({
				modal: true,
				overlayColor: '#0d4468',
				scrolling: 'no',
				href:  $link.attr('url'),
				type:  'iframe',
				width: ( ($link.attr('width')) ? parseInt($link.attr('width')) : 550),
				height: ( ($link.attr('height')) ? parseInt($link.attr('height')) : 300),
				onClosed: function () {
					//TODo: script fermeture
					$('#ihm-view .element:visible').each(function() {
						if ($(this).attr('old-query')) {
							$e = $(this);
							//refresh
							$.ajax({
								async:false,
								url: $(this).attr('old-query'),
								success: function(msg) {
									$e.html(msg);
								},
								error: function() {
									$('.path-element').eq($('.path-element').length-2).click();
								}
							});
						}
					});

					//listing
					if ($('#ihm-content-listing').attr('old-query')) {
						//refresh
						$.ajax({
							async:false,
							url: $('#ihm-content-listing').attr('old-query'),
							success: function(msg) {
								//$('#ihm-content-listing').html(msg);
								//$('#ihm-content-listing li#' + $oldid).addClass('selected');
							}
						});
					}

					return false;
				}
			});
		}
		return false;
	});
    
	// call search first
    setTimeout(function() { 
		$('#search-content').addClass('first-click').click();
	}, 500);
	
	//search manager
	$('li#search-content').live('click', function() {
		$element = $(this);
		$.ajax({
		   url: $(this).attr('url'),
		   beforeSend: function () {
			    if (!$element.hasClass('first-click')) {
			    	$('#ihm-view .element').hide();
					$('#ihm-content-listing').empty();
					wait_block('ihm-content-listing', JAVASCRIPT_WAIT);
			    }
		   },
		   success: function (message, status) {
			    $('#ihm-view-search').remove();
		    	$('#ihm-view').append(message);
		    	$('#ihm-view-search').fadeIn();
		   },
		   complete: function () {
			   $('#objwait').remove();
			   
			   
			   if (!$element.hasClass('first-click')) {
				   if ($element.hasClass('navigator')) {
					   // add element to pathfinder
					   pathfinder($element);
				   }
			   }
			   else {
			    	$element.removeClass('first-click');
			   }
			   
			   //add class selected
			   $element.parent().find('li').each(function() {
				   $(this).removeClass($(this).attr('id') + '-selected');
			   });
			   $element.addClass($element.attr('id') + '-selected').addClass('selected');
		   }
		});
		return false;
	});
});

//change generic
$('.generic').live('change', function () {
	   if ($(this).val() != '') {
		  _generic = $(this).parent();
		  $clone = _generic.clone();
		  $clone.find('input, .extra').remove();
	  	  //check if function or extras
		  switch ($(this).val()) {
		  case 'function':
			  //call new list from ajax
			  $el = $(this);
		      $.ajax({
				  url: $el.attr('query') + '/key/function',
				  async: true,
				  dataType:'json',
				  beforeSend: function () {
			    	 wait_block($el.attr('id'), '');
			      },
				  success: function (data) {
			    	  if (data.mode == 'text') {
			    		  $el.parent().append('<input type="text" class="textfield" name="value[]" minlength="3" /> - <span class="remove"><img src="'+baseurl+'/img-pack/application/buttons/remove-extra.png" width="15"/></span>');
			    	  }
			    	  else {
				    	 _options = '<option>CHOOSE A FUNCTION</option>';
				    	 //create select or nothing = error
				    	 $.each(data, function(i,item){
				    		 _options += '<option value="'+ i +'">'+ item +'</option>';
				    	 });
				    	 $el.parent().append('<select class="textfield" name="value[]">'+ _options +'</select> - <span class="remove"><img src="'+baseurl+'/img-pack/application/buttons/remove-extra.png" width="15"/></span>');
			    	  }
			      },
				  error: function() {
					  $el.parent().append('<input type="text" class="textfield" name="value[]" minlength="3" /> - <span class="remove"><img src="'+baseurl+'/img-pack/application/buttons/remove-extra.png" width="15"/></span>');
				  }
			  });
			  break;
		  case 'extra':
			  //call new list from ajax
			  $el = $(this);
		      $.ajax({
				  url: $el.attr('query') + '/key/extra',
				  async: true,
				  dataType:'json',
				  beforeSend: function () {
			    	 wait_block($el.attr('id'), '');
			      },
				  success: function (data) {
			    	 _options = '<option>CHOOSE EXTRA KEY</option>';
			    	 //create select or nothing = error
			    	 $.each(data, function(i,item){
			    		 _options += '<option value="'+ i +'">'+ item +'</option>';
			    	 });
			    	 $el.html(_options);
			      },
				  complete: function() {
					  $el.parent().append('<input type="text" class="textfield" name="value[]" minlength="3" /> - <span class="remove"><img src="'+baseurl+'/img-pack/application/buttons/remove-extra.png" width="15"/></span>');
				  }
			  });
			  break;
			  default:
				  //add genric text
				  $(this).parent().append('<input type="text" class="textfield" name="value[]" minlength="3" /> - <span class="remove"><img src="'+baseurl+'/img-pack/application/buttons/remove-extra.png" width="15"/></span>');
				  break;
		  }
		  
		  //add new line
		  $clone.insertAfter(_generic);
	  	  $(this).removeClass('generic');
	  	  $('span.remove').css('cursor', 'pointer');
	   }
	   return false;
});

//remove generic 
$('span.remove').live('click', function(e) {
		$(this).parent().fadeOut(500, function () {
			$(this).remove();
		});
		return false;
});


// click path element generic
var access_path = function (el) {
	$element = $(el);
	$.ajax({
	   url: $element.attr('url'),
	   beforeSend: function () {
			$('#ihm-view .element').hide();
			wait_block('ihm-content-listing', JAVASCRIPT_WAIT);
	   },
	   success: function (message, status) {
	    	if (message != $('#ihm-content-listing').html()) {
				$('#ihm-content-listing').html(message);
				$('#ihm-content-listing').attr('old-query', $element.attr('url'));
			}
	   },
	   complete: function () {
		   $element.find('ul').eq(0).slideUp(function () {
			   $(this).empty();
		       // add selected
			   $element.parents('ul#pathroot').find('li').each(function() {
				    if ($(this).attr('id') != $element.attr('id')) {
				    	if ($(this).attr('id')) {
							$(this).removeClass($(this).attr('id') + '-selected');
						}
						else {
							$(this).removeClass('selected');
						}
				    }
			   });
			   
			   //block height
			   if ($('li#root ul li').length > 3) {
					$('#pathfinder-rooter').css({
						height: '54px',
						overflow: 'hidden'
					});
					$('#pathfinder-navigator').css('visibility', 'visible');
			   }
			   else {
					$('#pathfinder-rooter').removeAttr('style');
					$('#pathfinder-navigator').css('visibility', 'hidden');
			   }
			   //$('.ihm-content').parent().equalHeight();
			   $('#ihm-content').css('height', $('.ihm-content').height() - $('#ihm-pathfinder').height()); 
			   
		   });
		   
		   $element.addClass($element.attr('id') + '-selected'); // patch for All .addClass('selected')
		   //$element.find('.path-element-counter').hide();
		   $("#ihm-content .content").css({top:0});
		   setTimeout(function () {
			   //callback person
			   callback();
		   }, 400);
	  }
	});
};

var searching = function(data, target) {
	$('#ihm-content-listing').html(data);
	var objconfirm = '<div id="objconfirm" style="position:absolute; background:#333; color:#fff; text-transform:uppercase; ' +
    'width:100%; height:'+($('#ihm-content-listing').parent().parent().height() + 50)+'px; opacity:0.90; moz-opacity:0.90; top:0; left:0; ' +
    'filter:alpha(opacity=90);" align="center">' +
    '<img src="'+ baseurl +'/img-pack/application/pictos/close-modal-search.png" style="position:absolute; top:5px; right:5px; cursor:pointer;" onclick="$(\'#objconfirm\').remove();">'+
    '<br/><br/><br/><small>'+JAVASCRIPT_SEARCH_INFORMATIONS+'</small></div>';
	$('#' + target).append(objconfirm);
};
